package cn.edu.tsinghua.weibo.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.tsinghua.weibo.entity.User;
import cn.edu.tsinghua.weibo.util.DB;

@SuppressWarnings("serial")
public class Search extends HttpServlet {

	String SQL = "select * from user where nick like ?";

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String usernick = request.getParameter("usernick");

		usernick = "%" + usernick + "%";

		try {
			Connection connection = DB.getConnection();
			PreparedStatement preparedStatement = connection.prepareStatement(SQL);
			preparedStatement.setString(1, usernick);

			ResultSet resultSet = preparedStatement.executeQuery();
			ArrayList<User> arrayList = new ArrayList<User>();
			while (resultSet.next()) {
				User user = new User();
				user.setId(resultSet.getInt("id"));
				user.setNick(resultSet.getString("nick"));
				user.setAvatar(resultSet.getString("avatar"));
				arrayList.add(user);
				HttpSession session = request.getSession();
				session.setAttribute("users", arrayList);
			}

			DB.close(resultSet, preparedStatement, connection);
			response.sendRedirect("search.jsp");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
